package com.hoshiicloud.saleorder.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hoshiicloud.common.aop.Logable;
import com.hoshiicloud.common.exception.CommonError;
import com.hoshiicloud.common.exception.QueryException;
import com.hoshiicloud.common.exception.ServiceException;
import com.hoshiicloud.common.query.OmnipotentParam;
import com.hoshiicloud.common.query.OmnipotentWrapper;
import com.hoshiicloud.saleorder.entity.OrderMain;
import com.hoshiicloud.saleorder.feign.IdGeneratorService;
import com.hoshiicloud.saleorder.mapper.OrderMainMapper;
import com.hoshiicloud.saleorder.service.OrderMainService;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 订单信息 服务实现类
 * </p>
 *
 * @author zhangshuhu
 * @since 2019-06-03
 */
@Slf4j
@Service
public class OrderMainServiceImpl extends ServiceImpl<OrderMainMapper, OrderMain> implements
        OrderMainService {

    @Autowired
    private IdGeneratorService idGeneratorService;


    private Long id;

    /**
     * @param id
     * @return com.hoshiibuy.saleorder.entity.OrderMain
     * @description: 根据id查询订单信息
     */
    @Override
    // @Cacheable(cacheNames = "OrderMain", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#id")
    @Logable(authName = "销售订单-订单信息-查询订单信息 ")
    public OrderMain getById(Long id) {
        this.id = id;
        OrderMain orderMain = baseMapper.selectById(id);
        return Optional.ofNullable(orderMain)
                .orElseThrow(() -> new QueryException("无法找到订单信息记录"));
    }

    /**
     * @param entity
     * @return boolean
     * @description: 新增订单信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "OrderMain", allEntries = true)
    @Logable(authName = "销售订单-订单信息-新增订单信息")
    public boolean save(OrderMain entity) {

        return Optional.ofNullable(entity).map(orderMain -> {
            //String id = idGeneratorService.queryGeneratorId();
//            log.error("{}", id);
//
//            if (StrUtil.isBlank(id)) {
//                log.error("id生成异常");
//                throw new ServiceException(CommonError.error("网络开小差啦~, 请重新尝试"));
//            }

            //orderMain.setId(Long.parseLong(id));
            orderMain.setCreatedTime(LocalDateTime.now());

            int row = baseMapper.insert(orderMain);
            if (row <= 0) {
                log.error("新增优惠抵现单异常");
                throw new ServiceException(CommonError.error("新增订单信息失败"));
            }
            return true;
        }).orElseThrow(() -> new ServiceException(CommonError.error("新增订单信息失败，保存对象为空")));
    }

    /**
     * @param entity
     * @return boolean
     * @description: 修改订单信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "OrderMain", allEntries = true)
    @Logable(authName = "销售订单-订单信息管理-修改订单信息")
    public boolean updateById(OrderMain entity) {

        entity.setUpdatedTime(LocalDateTime.now());
        int row = baseMapper.updateById(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("修改订单信息失败"));
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "OrderMain", allEntries = true)
    @Logable(authName = "销售订单-订单信息管理-批量修改订单信息")
    public boolean updateByList(List<OrderMain> list) {
        return this.updateBatchById(list);
    }

    /**
     * @param queryWrapper
     * @return IPage
     * @description: 分页查询订单信息
     */
    @Override
    @Logable(authName = "销售订单-订单信息管理-分页查询订单信息")
    @Cacheable(cacheNames = "OrderMain", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+ T(com.hoshiicloud.common.utils.DigestUtils).md5(#key)")
    public IPage<OrderMain> page(IPage<OrderMain> page, Wrapper<OrderMain> queryWrapper, String key) {

        return baseMapper.selectPage(page, queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "OrderMain", allEntries = true)
    @Logable(authName = "销售订单-订单信息管理-删除订单信息")
    public boolean deleteById(Long id) {
        OrderMain entity = this.getById(id);

        return Optional.ofNullable(entity).map(orderMain -> {
            orderMain.setUpdatedTime(LocalDateTime.now()).setDeleted(1);
            int row = baseMapper.updateById(orderMain);
            if (row <= 0) {
                throw new ServiceException(CommonError.error("删除失败"));
            }
            return true;

        }).orElseThrow(() -> {
            log.error("删除订单信息异常，无法找到订单信息记录");
            return new QueryException("删除订单信息异常，无法找到订单信息记录");
        });
    }

    @Override
    @Cacheable(cacheNames = "OrderMain", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#key")
    @Logable(authName = "销售订单-订单信息管理-根据id集合查询订单信息")
    public List<OrderMain> getByIds(List<Long> ids, String key) {
        return baseMapper.selectBatchIds(ids);
    }

    /**
     * 根据自定义条件查询商品主单信息
     */
    @Override
    @Cacheable(cacheNames = "OrderMain", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#key")
    public List<OrderMain> omniQueryOrderMain(List<OmnipotentWrapper> wrappers, String key) {
        OmnipotentWrapper<OrderMain> omnipotentWrapper = new OmnipotentWrapper();
        QueryWrapper<OrderMain> wrapper = omnipotentWrapper.getWrapper(wrappers);
        return baseMapper.selectList(wrapper);
    }


}